package com.ixuestar.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/*******************************************************************************
 * FileControl 是一个用于处理文件的功能包，主要是复制文件，重命名文件、删除文件、存储文件、删除文件夹等
 *
 * @author Sunshine
 * @ClassName: FileControl
 * @Description: TODO
 * @author travbao@163.com
 * @date 06, 13, 2019 9:28:28 AM
 */
public class FileControl {

    // 文件复制
    public static boolean copyFile(String source, String copy) throws Exception {

        File source_file = new File(source);
        File copy_file = new File(copy);

        // BufferedStream缓冲字节流

        if (!source_file.exists()) {
            throw new IOException("文件复制失败：源文件（" + source_file + "） 不存在");
        }
        if (copy_file.isDirectory()) {
            throw new IOException("文件复制失败：复制路径（" + copy_file + "） 错误");
        }
        File parent = copy_file.getParentFile();
        // 创建复制路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        // 创建复制文件
        if (!copy_file.exists()) {
            copy_file.createNewFile();
        }

        FileInputStream fis = new FileInputStream(source_file);
        FileOutputStream fos = new FileOutputStream(copy_file);

        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] KB = new byte[1024];
        int index;
        while ((index = bis.read(KB)) != -1) {
            bos.write(KB, 0, index);
        }

        bos.close();
        bis.close();
        fos.close();
        fis.close();

        if (!copy_file.exists()) {
            return false;
        } else if (source_file.length() != copy_file.length()) {
            return false;
        } else {
            return true;
        }

    }

    // 文件重命名
    public static boolean renameFile(String url, String new_name) throws Exception {
        String old_url = url;
        old_url = old_url.replace("\\", "/");
        File old_file = new File(old_url);
        if (!old_file.exists()) {
            throw new IOException("文件重命名失败，文件（"+old_file+"）不存在");
        }
        System.out.println(old_file.exists());

        String old_name = old_file.getName();
        // 获得父路径
        String parent = old_file.getParent();
        // 重命名
        String new_url = parent + "/" + new_name;
        File new_file = new File(new_url);
        old_file.renameTo(new_file);

        System.out.println("原文件：" + old_file.getName());
        System.out.println("新文件：" + new_file.getName());
        new_name = new_file.getName();
        old_name = old_file.getName();
        if (new_name.equals(old_name)) {
            return false;
        } else {
            return true;
        }

    }

    // 文件删除
    public static boolean deleteFile(String url) throws Exception {
        url = url.replace("\\", "/");
        File file = new File(url);

        if (file.isFile()) {
            if (file.exists()) {
                file.delete();
            }
        }else{
            throw new IOException("文件删除失败：（"+file+"）错误");
        }
        if (file.exists()) {
            return false;
        } else {
            return true;
        }
    }

    // 创建文件夹
    public static boolean createPath(String url) throws Exception {
        url = url.replace("\\", "/");
        File folder = new File(url);
        if(!folder.isDirectory()){
            throw new IOException("创建文件夹失败：（"+folder+"）不是文件夹路径");
        }

        if (!folder.isFile()) {
            if (!folder.exists()) {
                folder.mkdirs();
            }
        }
        // 检测是否创建成功
        if (folder.isDirectory() && folder.exists()) {
            return true;
        } else {
            return false;
        }

    }


    /**
     * @ 存储文件
     * @ param inputStream
     * @ param path
     * @throws IOException
     */
    @SuppressWarnings("resource")
    public static void cunFile(InputStream inputStream,String path) throws IOException {
        // 通过url获取文件

        // 通过inputStream获取文件
//	        InputStream inputStream = new FileInputStream(f);
        // 定义一个文件名字进行接收获取文件
        FileOutputStream fileOut = new FileOutputStream(new File(path));
        byte[] buf = new byte[1024 * 8];
        while (true) {
            int read = 0;
            if (inputStream != null) {
                read = inputStream.read(buf);
            }
            if (read == -1) {
                break;
            }
            fileOut.write(buf, 0, read);
        }
        // 查看文件获取是否成功
        if (fileOut.getFD().valid() == true) {
            System.out.println("获取文件保存成功");
        } else {
            System.out.println("获取文件失败");
        }
        fileOut.flush();
    }

    /**
     * @ 删除文件夹
     * @ param path
     * @ return
     */
    public static boolean deleteDir(String path){
        File file = new File(path);
        if(!file.exists()){//判断是否待删除目录是否存在
            System.err.println("The dir are not exists!");
            return false;
        }

        String[] content = file.list();//取得当前目录下所有文件和文件夹
        for(String name : content){
            File temp = new File(path, name);
            if(temp.isDirectory()){//判断是否是目录
                deleteDir(temp.getAbsolutePath());//递归调用，删除目录里的内容
                temp.delete();//删除空目录
            }else{
                if(!temp.delete()){//直接删除文件
                    System.err.println("Failed to delete " + name);
                }
            }
        }
        //删除空目录
        boolean success = (new File(path)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + path);
        } else {
            System.out.println("Failed to delete empty directory: " + path);
        }
        return true;
    }

    /**
     * @ 删除文件
     * @ param fileName
     * @ return
     */
    public static boolean deleteFiles(String fileName){
        File file = new File(fileName);
        if(file.isFile() && file.exists()){
            Boolean succeedDelete = file.delete();
            if(succeedDelete){
                System.out.println("删除单个文件"+fileName+"成功！");
                return true;
            }
            else{
                System.out.println("删除单个文件"+fileName+"失败！");
                return true;
            }
        }else{
            System.out.println("删除单个文件"+fileName+"失败！");
            return false;
        }
    }

    /**
     * @ 阅读文件
     * @ param in
     */
    public static void ReadFile(InputStream in){
        byte b[] = new byte[1024];
        int len = 0;
        int temp=0;          //所有读取的内容都使用temp接收
        try {
            System.out.println(in.read());
            while((temp=in.read())!=-1){    //当没有读取完时，继续读取
                b[len]=(byte)temp;
                len++;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(new String(b,0,len));
    }


    /**
     * @throws Exception
     * @ 删除目录（文件夹）以及目录下的文件
     * @ param   sPath 被删除目录的文件路径
     * @ return  目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String sPath) throws Exception {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * * 删除空目录
     * @ param dir 将要删除的目录路径
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }
    
    
    /**
	 * 文件上传方法
	 * @param file 文件byte[]
	 * @param filePath 文件上传路径
	 * @param fileName 文件保存路径
	 * @throws IOException 
	 * @throws Exception
	 * void
	 */
    public static void uploadFile(byte[] file, String filePath, String fileName) throws IOException{
 
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
   }

}
